package com.example.whatrubbish.service.impl;

import com.example.whatrubbish.mapper.QuestionMapper;
import com.example.whatrubbish.model.Question;
import com.example.whatrubbish.service.QuestionService;
import com.example.whatrubbish.vo.Criteria;
import com.example.whatrubbish.vo.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class QuestionServiceImpl implements QuestionService {
    @Autowired
    QuestionMapper questionMapper;

    @Override
    public List<Question> selectRand() {
        return questionMapper.selectRand();
    }

    @Override
    public PageBean<Question> selectByCondition(Integer pageIndex, Integer pageSize, String title) {
        Criteria criteria = new Criteria();
        criteria.addExtField("pageIndex", pageIndex <= 1 ? 0 : (pageIndex - 1) * pageSize);
        criteria.addExtField("pageSize", pageSize);
        criteria.addExtField("title", title);
        Long count = questionMapper.selectByQueryConditionCount(criteria);
        List<Question> list = questionMapper.selectByQueryCondition(criteria);
        PageBean<Question> pageBean = new PageBean<>(pageIndex <= 0 ? 1 : pageIndex, pageSize);
        pageBean.setResultList(list);
        pageBean.setTotalCount(count);
        return pageBean;
    }

    @Override
    public int insert(Question question) {
        question.setCreatetime(new Date());
        return questionMapper.insertSelective(question);
    }

    @Override
    public int update(Question question) {
        question.setUpdatetime(new Date());
        return questionMapper.updateByPrimaryKeySelective(question);
    }

    @Override
    public int delete(Integer id) {
        return questionMapper.deleteByPrimaryKey(id);
    }
}
